const config = require('../../config/index')
const { wxRequest } = require('../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: config.baseUrl, 
    countdown: 0,
    formData: {
      // 手机号
      phone:'',
      // 验证码
      captcha:'',
    },
    dynamicRules: [
      {
        name:'phone',
        rules: [
          {required:true, message:'请输入手机号'},
        ]
      },
      {
        name:'captcha',
        rules: [{required:true, message:'请输入验证码'}]
      },
    ],
    timer: null,
    theme: wx.getStorageSync('InvoiceLoanTheme') || ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      theme: wx.getStorageSync('InvoiceLoanTheme') || ''
    })
  },
  onUnload(){
    if(this.data.timer){
      clearInterval(this.data.timer)
    }
  },
  // 简易双向数据绑定
  handInputChange (e) {
    this.setData({
      [`formData.${e.target.id}`]: e.detail.value
    })
  },
  handleCode() {
    const phone = this.data.formData.phone
    if(this.data.countdown !== 0) {
      return
    }
    if(!phone) {
      wx.showToast({
        title: '请输入手机号',
        icon:'none'
      })
      return
    }
    if(phone){
      const regex = /^1(?:3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-9])\d{8}$/;
      if(!regex.test(phone)){
        wx.showToast({
          title: '请输入正确的手机号',
          icon:'none'
        })
        return
      }
    }
    this.fetchVerificationCode()
  },
  fetchVerificationCode() {
    const that = this
    const phone = that.data.formData.phone
    wxRequest({
      url: `${config.baseUrl}/captcha/send?phone=${phone}`,
      method:'POST',
      invalidCb(){
        that.fetchVerificationCode()
      },
      success(res){
        if(res.data.data) {
          wx.showModal({
            title: '验证码',
            content: res.data.data,
            showCancel: false,
            confirmColor: '#007EE6'
          })
        }
        that.setData({ countdown: 60 });
        // 设置倒计时定时器
        const timer = setInterval(() => {
          if (that.data.countdown <= 1) {
            clearInterval(timer);
            that.setData({ countdown: 0 });
          } else {
            that.setData({ countdown: that.data.countdown - 1 });
          }
        }, 1000);
        that.setData({
          timer
        })
      }
    })
  },
  login(){  
    const that = this
    const { phone,captcha } = that.data.formData  
    wxRequest({
      url: `${config.baseUrl}/captcha/confirm`,
      method: 'POST',
      data: {
        captcha,
	      phone
      },
      invalidCb(){
        that.login()
      },
      success(){
        const { phone } = that.data.formData
        const oldPhone = wx.getStorageSync('InvoiceLoanPhone')
        if(oldPhone && oldPhone!== phone) {
          wx.setStorage({
            key: 'InvoiceLoanAccountUserId',
            data: ''
          })
        }
        wx.setStorage({
          key: 'InvoiceLoanPhone',
          data: `${phone}`
        })
        wx.navigateTo({
          url: '/pages/identityAuthentication/index',
        })
      },
    })
  },
  handleLogin(){
    const that = this
    const { phone } = this.data.formData
    const regex = /^1(?:3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-9])\d{8}$/;
    this.selectComponent('#detailForm').validate(async(valid, errors) => {
      if(valid) { 
        if(!regex.test(phone)){
          wx.showToast({
            title: '请输入正确的手机号',
            icon:'none'
          })
          return
        }
        that.login()
      } else {
        const firstError = Object.keys(errors)
        if(firstError.length) {
          wx.showToast({
            title: errors[firstError[0]].message,
            icon: 'none'
          })
        }
      }
    })
  }
})